package com.dup.jxlh.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dup.jxlh.admin.entities.model.Department;
import com.dup.jxlh.admin.mapper.DepartmentMapper;
import com.dup.jxlh.admin.service.DepartmentService;
import com.dup.jxlh.admin.service.OwnValidatorService;
import com.dup.jxlh.api.entities.PaginationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;

@Service("departmentServiceImpl")
public class DepartmentServiceImpl implements DepartmentService {
    @Resource
    private DepartmentMapper departmentMapper;

    @Autowired
    private OwnValidatorService ownValidatorService;

    @Override
    public Page<Department> getDepartmentList(PaginationData paginationData) {
        Page<Department> departmentPage = new Page<>(paginationData.getCurrent(), paginationData.getSize());
        departmentPage.setOptimizeCountSql(false);

        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        ownValidatorService.setQueryWrapperByCompany(queryWrapper, paginationData);

        if (!paginationData.getSearch().isEmpty()) {
            queryWrapper.like("name", paginationData.getSearch());
        }

        ArrayList<Department> departmentList = departmentMapper.getDepartmentList(departmentPage, queryWrapper);
        if (departmentList != null) {
            departmentPage.setRecords(departmentList);
        }
        return departmentPage;
    }

    @Override
    public Boolean addDepartment(Department department) {
        if (departmentMapper.insert(department) == 1) {
            return true;
        }
        return false;
    }

    @Override
    @CacheEvict(value = "department", key = "#department.id")
    public Boolean editDepartment(Department department) {
        if (departmentMapper.updateById(department) == 1) {
            return true;
        }
        return false;
    }

    @Override
    @Cacheable(value = "department", key = "#departmentId")
    public Department getDepartment(BigInteger departmentId) {
        return departmentMapper.selectById(departmentId);
    }
}
